<template>
  <div class="consultation-page">
    <van-nav-bar :title="$t('consultation.title')" left-arrow @click-left="onClickLeft" />

    <div class="consultation-content">
      <!-- 对话区 -->
      <div class="chat-area" ref="chatAreaRef">
        <div v-for="(msg, idx) in messages" :key="idx" :class="['chat-bubble', msg.role]">
          <div v-if="msg.role === 'assistant'" class="avatar">
            <img src="../assets/ai-avatar.png" alt="AI Assistant" />
          </div>
          <span>{{ msg.content }}</span>
        </div>
      </div>
      <!-- AI 问候语和说明（首次进入时显示） -->
      <div v-if="messages.length === 0" class="ai-greeting">
        <div class="ai-bubble">
          {{ t('consultation.greeting') }}
        </div>
      </div>
      <!-- 快捷提问卡片 -->
      <div class="quick-questions">
        <van-cell-group>
          <van-cell v-for="(q, idx) in quickQuestions" :key="idx" clickable @click="onQuickQuestion(q)">
            <template #icon>
              <span class="hashtag">#</span>
            </template>
            <span>{{ t(q) }}</span>
          </van-cell>
        </van-cell-group>
      </div>
    </div>
    <!-- 底部功能栏 -->
    <div class="consultation-footer">
      <div class="footer-actions">
        <van-button size="small" round icon="bulb-o" class="footer-btn">{{ t('consultation.smartThink') }}</van-button>
        <van-button size="small" round icon="comment-o" class="footer-btn">{{ t('consultation.reportRead')
          }}</van-button>
        <van-button size="small" round icon="apps-o" class="footer-btn">{{ t('consultation.medRecognize')
          }}</van-button>
      </div>
      <div class="footer-input">
        <van-button icon="microphone-o" class="voice-btn" plain shape="circle" size="small" />
        <input class="input-bar" :placeholder="t('consultation.inputPlaceholder')" v-model="inputText"
          @keyup.enter="onSend" />
        <van-button icon="plus" class="plus-btn" plain shape="circle" size="small" />
        <van-button type="primary" size="small" class="send-btn" @click="onSend">{{ t('consultation.send')
          }}</van-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useChat, useChat2 } from '../utils/WebAPI'

const { t } = useI18n()
const router = useRouter()
const inputText = ref('')
const chatAreaRef = ref<HTMLElement | null>(null)

const quickQuestions = ref([
  'consultation.quick1',
  'consultation.quick2',
  'consultation.quick3'
])

// 之后这里可以抽离到utils中（hooks函数）
const { messages, total_res, start, bigModel } = useChat()
const { result, startAI, chat_history, bigModel: bigModel2 } = useChat2()
bigModel.onWillStatusChange = function (oldStatus, status) {
  // 可以在这里进行页面中一些交互逻辑处理：按钮交互等
  if (status === 'init') {
    chat_history.value = JSON.stringify(messages.value)
    startAI()
  }

};
bigModel2.onWillStatusChange = function (oldStatus, status) {
  // 可以在这里进行页面中一些交互逻辑处理：按钮交互等
  if (status === 'init') {
    console.log(result.value);
    const splitReg = /\d\./
    const str = result.value.split(splitReg);
    const res = str.map(item => item.trim().replace(/\n/, '')).filter(item => item !== '');
    quickQuestions.value = res;
  }
};


const onClickLeft = () => {
  router.back()
}

const onQuickQuestion = (key: string) => {
  inputText.value = t(key)
  onSend()
}

const onSend = () => {
  const text = inputText.value.trim()
  if (!text) return
  messages.value.push({ role: 'user', content: text })
  inputText.value = ''
  // 模拟AI回复
  setTimeout(() => {
    start();

    messages.value.push({ role: 'assistant', content: total_res })
    // messages.value.push({ role: 'assistant', content: t('consultation.aiReply') })
    nextTick(() => {
      scrollToBottom()
    })
    // 跳转到 https://appbuilder.bce.baidu.com/ai_apaas/share/home?short_code=zyi7CP7KIww&source=web
    // location.href="https://appbuilder.bce.baidu.com/ai_apaas/share/home?short_code=zyi7CP7KIww&source=web"
    // location.href="https://appbuilder.bce.baidu.com/ai_apaas/share/home?short_code=zyi7CP7KIww&source=web"
  }, 800)
  nextTick(() => {
    scrollToBottom()
  })
}

const scrollToBottom = () => {
  if (chatAreaRef.value) {
    chatAreaRef.value.scrollTop = chatAreaRef.value.scrollHeight
  }
}

onMounted(() => {
  scrollToBottom()
  messages.value.shift();
  // 初始化TTSRecorder
  // let bigModel = new TTSRecorder();
})
</script>

<style lang="scss" scoped>
.consultation-page {
  min-height: 100vh;
  background: linear-gradient(180deg, #eaf6ff 0%, #f7f8fa 100%);
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.consultation-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  padding: 16px 0 100px 0; // 预留底部栏空间
  min-height: 0;
}

.chat-area {
  flex: 1;
  min-height: 120px;
  max-height: 100vh;
  max-height: 100vh;
  overflow-y: auto;
  padding: 0 16px 8px 16px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.chat-bubble {
  display: inline-block;
  padding: 10px 16px;
  border-radius: 16px;
  font-size: 15px;
  max-width: 80%;
  word-break: break-all;
  margin-bottom: 2px;
  position: relative;

  .avatar {
    position: absolute;
    top: -30px;
    left: 0;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    overflow: hidden;
    background: #fff;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
}

.chat-bubble.user {
  align-self: flex-end;
  background: linear-gradient(90deg, #3b8cff 0%, #6ec6ff 100%);
  color: #fff;
}

.chat-bubble.assistant {
  align-self: flex-start;
  background: #fff;
  color: #333;
  border: 1px solid #e6e6e6;
  margin-top: 35px; // 为头像留出空间
}

.ai-greeting {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 16px;

  .ai-bubble {
    background: #fff;
    border-radius: 12px;
    padding: 16px;
    font-size: 16px;
    color: #333;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
    max-width: 90%;
  }
}

.quick-questions {
  .van-cell {
    margin-bottom: 12px;
    background: #f6f8fa;
    border-radius: 8px;

    .hashtag {
      color: #3b8cff;
      font-weight: bold;
      margin-right: 8px;
    }
  }
}

.consultation-footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #f7f8fa;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.03);
  padding: 8px 0 8px 0;
  z-index: 10;

  .footer-actions {
    display: flex;
    justify-content: space-around;
    margin-bottom: 8px;

    .footer-btn {
      background: #fff;
      color: #3b8cff;
      border: none;
      font-size: 14px;
      padding: 0 12px;
    }
  }

  .footer-input {
    display: flex;
    align-items: center;
    background: #fff;
    border-radius: 24px;
    margin: 0 12px;
    padding: 4px 8px;

    .voice-btn,
    .plus-btn {
      background: transparent;
      color: #3b8cff;
      border: none;
    }

    .input-bar {
      flex: 1;
      border: none;
      outline: none;
      font-size: 16px;
      background: transparent;
      margin: 0 8px;
    }

    .send-btn {
      margin-left: 4px;
      background: #3b8cff;
      color: #fff;
      border: none;
      border-radius: 16px;
      padding: 0 12px;
    }
  }
}
</style>